#-*- coding:utf-8 -*-

from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.csrf import csrf_exempt
from django.utils import simplejson
from forum.models import Board, Article, Comment, UserAct
from forum.forms import AddArticleForm, UploadImageForm
from forum.manager import setUserImage

ARTICLE_NUM_OF_PAGE = 10


def index(request):
    return render(request, "forum/index.html", {'boards':Board.objects.all()})


def article_detail(request, article_id):
    _articleid = int(article_id)
    article = get_object_or_404(Article, pk=_articleid)
    article.reads = article.reads + 1
    article.save()
    return render(request, "forum/article_detail.html", {"article": article}) 


def latest_articles(request, page_num):
    _pagenum = int(page_num)
    article_qs = Article.objects.filter(status=Article.STATUS_NORMAL)
    paginator = Paginator(article_qs, ARTICLE_NUM_OF_PAGE)

    try:
        article_list = paginator.page(page_num)
    except EmptyPage:
        article_list = paginator.page(paginator.num_pages)

    return render(request, "forum/article_list.html", {'article_list': article_list, 'page':paginator})


def article_list(request, board_id, page_num):
    _boardid = int(board_id)
    _pagenum = int(page_num)

    board = get_object_or_404(Board, pk=_boardid)
    article_qs = Article.objects.filter(status=Article.STATUS_NORMAL, board_id = _boardid)

    paginator = Paginator(article_qs, ARTICLE_NUM_OF_PAGE)

    try:
        article_list = paginator.page(page_num)
    except EmptyPage:
        article_list = paginator.page(paginator.num_pages)

    return render(request, "forum/article_list.html", {'article_list': article_list, 'page':paginator,'board':board})


@login_required
def add_article(request):
    if request.method == 'GET':
        f = AddArticleForm()
        imgform = UploadImageForm()
        return render(request, "forum/add_article.html", {"form":f, "imgform":imgform})
        
    f = AddArticleForm(request.POST)
    if f.is_valid():
        article = f.save(False)
        article.author = request.user
        article.save()

        for imgname in request.POST.getlist('userimg', []):
            setUserImage(request.user, imgname, article)

        return redirect("/forum/article/%d/"%(article.id))

    else:
        imgform = UploadImageForm()
        return render(request, "forum/add_article.html", {"form":f, "imgform":imgform})


@login_required
@csrf_exempt
def comment(request, article_id):
    _articleid = article_id
    if request.method != 'POST': 
        raise Http404()

    content = request.POST.get('content', '') 
    if len(content) == 0:
        raise Http404()

    article = get_object_or_404(Article, pk=_articleid)
    json = {}
    c = Comment()
    c.article = article
    c.author = request.user
    c.content = content
    c.save()
    json['ret'] = True
    json['author'] = request.user.username
    json['content'] = content
    json['posttime'] = c.posttime.strftime("%Y-%m-%d %H:%M:%S") 
    article.comments = article.comments + 1
    article.save()

    return HttpResponse(simplejson.dumps(json))


@login_required
def user_act(request, article_id, act):
    _articleid = int(article_id)
    if act not in (UserAct.ACT_ZAN, UserAct.ACT_SAVE):
        raise Http404()

    article = get_object_or_404(Article, pk=_articleid)
    json_ret = {}
    qs = UserAct.objects.filter(user=request.user, article_id=_articleid, act=act)
    if len(qs)!= 0:
        json_ret['ret'] = 'fail' 
        json_ret['err'] = 'duplicated operation'
        return HttpResponse(simplejson.dumps(json_ret))

    useract = UserAct()
    useract.user = request.user
    useract.article = article
    useract.act = act 
    useract.save()

    if act == USER_ACT_ZAN: article.zans = article.zans + 1
    if act == USER_ACT_SAVE: article.saves = article.saves+ 1
    article.save()

    json_ret['ret'] = 'ok' 
    return HttpResponse(simplejson.dumps(json_ret))


@login_required
def upload_image(request):
    if request.method == 'GET':
        f = UploadImageForm()
        return render(request, "forum/upload.html", {"form":f})
    else:
        f = UploadImageForm(request.POST, request.FILES)
        if f.is_valid():
            img = f.save(False)
            img.owner= request.user
            img.size = img.image.size
            img.save()
            img.relative_path = img.image.name
            img.save()

            imgurl = "/static/%s/" % (img.image.name)
            return render(request, "forum/upload_iframe.html", {"imgurl":imgurl, "imgname":img.image.name})

        return HttpResponse("What ???")

